# -*- coding: utf-8 -*-
import scrapy


class MmonlyTagSpider(scrapy.Spider):
    name = 'mmonly_tag'
    allowed_domains = ['www.mmonly.cc']
    start_urls = ['http://www.mmonly.cc/tag/']

    def parse(self, response):
        datas = response.xpath(
            '//div[@class="Clbc_Game TagBox"]/h2|//div[@class="Clbc_Game TagBox"]/div[@class="TagList"]')
        for data in datas:
            parent_tag = data.xpath('./text()').extract()
            if len(parent_tag) > 0:
                chil_elems = datas[datas.index(data) + 1].xpath('./a')
                for chil_elem in chil_elems:
                    item = {}
                    item['parent_tag'] = parent_tag[0]
                    item['children_tag'] = chil_elem.xpath('./text()').extract()[0]
                    herf = chil_elem.xpath('./@href').extract()
                    herf = "http://www.mmonly.cc" + herf[0]
                    print("\n" + herf + "\n")

                    yield scrapy.Request(
                        herf,
                        callback=self.get_tag_detail,
                        meta={
                            'item': item
                        }
                    )

    def get_tag_detail(self, response):
        item = response.meta['item']
        tag_txt = response.xpath('//div[@class="TagTxt"]/p/text()').extract()
        tag = response.xpath('//div[@class="TagTxt"]/h1/a/text()').extract()
        bg_image = response.xpath('//body/@style').extract()
        bg_image = '' if len(bg_image) == 0 else bg_image[0].replace('background:url(', '').replace(
            ') no-repeat center 72px;', '')
        item['tag'] = '' if len(tag) == 0 else tag[0]
        item['tag_txt'] = '' if len(tag_txt) == 0 else tag_txt[0]
        item['bg_image'] = bg_image
        yield item
